class Solution(object):
    def minFallingPathSum(self, matrix):
        n = len(matrix)
        last = matrix[0]
        index = 1
        while index < n:
            next_list = [float('inf')] * n
            for i in range(n):
                if i - 1 >= 0:
                    next_list[i - 1] = min(next_list[i - 1], last[i] + matrix[index][i - 1])
                next_list[i] = min(next_list[i], last[i] + matrix[index][i])
                if i + 1 < n:
                    next_list[i + 1] = min(next_list[i + 1], last[i] + matrix[index][i + 1])
            last = next_list
            index += 1
        return min(last)




data = Solution()
matrix = [[-19,57],[-40,-5]]
print(data.minFallingPathSum(matrix))
